<template>
  <div class="prescription-page">
    <!-- 显示已保存的处方 -->
    <div class="saved-prescriptions">
      <!-- <h3>已保存的处方</h3> -->
      <!-- 新增一个容器用于纵向滚动 -->
      <div class="saved-prescriptions-scroll">
        <div
          v-for="(savedItem, index) in savedPrescriptions"
          :key="index"
          class="saved-prescription-item"
        >
          <el-form :model="savedItem" :inline="true" label-width="60px">
            <el-form-item label="药品编码">
              <el-input v-model="savedItem.code" readonly style="width: 80px;"/> <!-- 缩短药品编码输入框宽度 -->
            </el-form-item>
            <el-form-item label="药品名称">
              <el-input v-model="savedItem.name" readonly />
            </el-form-item>
            <el-form-item label="单价">
              <el-input v-model="savedItem.price" readonly />
            </el-form-item>
            <el-form-item label="数量">
              <el-input v-model="savedItem.count" readonly />
            </el-form-item>
            <el-form-item label="用法">
              <el-input v-model="savedItem.useage" readonly />
            </el-form-item>
            <el-form-item label="总价">
              <el-input v-model="savedItem.totalprice" readonly />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="savedItem.beizhu" readonly />
            </el-form-item>
            <el-form-item>
              <el-button type="danger" @click="deleteSavedPrescription(savedItem)">
                删除
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 增加分隔线 -->
    <div class="separator"></div>
    <!-- 处方新增列表 -->
    <div class="prescription-list">
      <div
        v-for="(item, index) in prescriptionList"
        :key="index"
        class="prescription-item"
      >
        <el-form :model="item" :inline="true" label-width="80px">
          <el-form-item label="药品编码">
            <el-input v-model="item.code" readonly />
          </el-form-item>
          <el-form-item label="药品名称">
            <el-select
              v-model="item.name"
              placeholder="请选择药品"
              filterable
              remote
              clearable
              :remote-method="() => searchDrugs(item)"
              :loading="loading"
              @change="handleDrugSelect(item)"
              @clear="clearDrugSelection(item)"
            >
              <el-option
                v-for="drug in item.drugOptions"
                :key="drug.code"
                :label="drug.name"
                :value="drug.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="单价">
            <el-input v-model="item.price" readonly />
          </el-form-item>
          <el-form-item label="数量">
            <el-input
              v-model.number="item.count"
              type="number"
              min="1"
              @input="calculatetotalprice(item)"
            />
          </el-form-item>
          <el-form-item label="用法">
            <el-select v-model="item.useage" placeholder="请选择用法">
              <el-option
                v-for="useage in useageList"
                :key="useage"
                :label="useage"
                :value="useage"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="总价">
            <el-input v-model="item.totalprice" readonly />
          </el-form-item>
          <el-form-item label="备注" class="beizhu-wide">
            <el-input v-model="item.beizhu" />
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="removePrescription(index)">
              删除
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-button type="primary" @click="addPrescription">添加处方</el-button>
    <el-button type="success" @click="savePrescription">保存处方</el-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { debounce } from "lodash";
import { getDrugs } from "@/api/drug/stock";
import { getSavedPrescriptions, deletePrescription, save} from "@/api/prescription/prescription";
import { ElMessage } from "element-plus";

const props = defineProps({
  clinicId: String, // 父组件传来的clinicId
});

onMounted(() => {
  console.log('Clinic ID:', props.clinicId); // 检查是否正确接收到 clinicId
});

const drugOptions = ref([]);
const loading = ref(false);
const savedPrescriptions = ref([]); // 用于存储已保存的处方

// 用法列表
const useageList = ["口服", "外用", "注射"];

// 处方列表
const prescriptionList = ref([
  {
    clinicId: props.clinicId,
    code: "",
    name: "",
    price: 0,
    count: 1,
    useage: "",
    totalprice: 0,
    beizhu: "",
    drugOptions: [], // 每个处方独立的药品选项
  },
]);

// 添加处方
const addPrescription = () => {
  const newItem = {
    clinicId: props.clinicId,
    code: "",
    name: "",
    price: 0,
    count: 1,
    useage: "",
    totalprice: 0,
    beizhu: "",
    drugOptions: [], // 初始化为空
  };
  prescriptionList.value.push(newItem);

  // 在添加新处方时加载药品数据
  getDrugsData("", newItem);
};

// 删除处方
const removePrescription = (index) => {
  prescriptionList.value.splice(index, 1);
};

// 处理药品选择
const handleDrugSelect = (item) => {
  const selectedDrug = item.drugOptions.find(
    (drug) => drug.name === item.name
  );
  if (selectedDrug) {
    item.code = selectedDrug.code;
    item.price = selectedDrug.price;
    calculatetotalprice(item);
  }
};

// 清除药品选择
const clearDrugSelection = (item) => {
  item.code = "";
  item.price = 0;
  item.totalprice = 0;
  item.name = "";
  item.drugOptions = []; // 清空当前处方的药品选项
};

// 计算总价
const calculatetotalprice = (item) => {
  item.totalprice = item.price * item.count;
};

// 获取药品列表
const getDrugsData = async (keyword = "", targetItem) => {
  try {
    loading.value = true;
    const response = await getDrugs(keyword);
    const fetchedDrugs = response.rows || [];
    if (targetItem) {
      targetItem.drugOptions = fetchedDrugs; // 更新指定处方的药品选项
    } else {
      drugOptions.value = fetchedDrugs; // 更新全局药品选项
    }
    loading.value = false;
  } catch (error) {
    console.error("Failed to fetch drugs:", error);
    loading.value = false;
  }
};

// 搜索药品
const searchDrugs = debounce((item) => {
  getDrugsData("", item); // 为当前处方加载药品数据
}, 300);

// 保存处方
const savePrescription = async () => {
  try {
    const response = await save(prescriptionList.value);
    if (response.code === 200) {
      ElMessage.success("处方保存成功");
      loadSavedPrescriptions(); // 刷新已保存的处方列表
    } else {
      ElMessage.error("处方保存失败");
    }
  } catch (error) {
    console.error("Failed to save prescription:", error);
    ElMessage.error("处方保存失败");
  }
};

// 加载已保存的处方
const loadSavedPrescriptions = async () => {
  try {
    const params = { 
      clinicId: props.clinicId
    };
    const response = await getSavedPrescriptions(params);
    savedPrescriptions.value = response.rows || []; // 将数据赋值给 savedPrescriptions
  } catch (error) {
    console.error("Failed to load saved prescriptions:", error);
    ElMessage.error("加载已保存处方失败");
  }
};

// 删除已保存的处方
const deleteSavedPrescription = async (savedItem) => {
  try {
    // 构造 ID 数组
    const ids = [savedItem.id];

    const response = await deletePrescription(ids);
    if (response.code === 200) {
      ElMessage.success("处方删除成功");
      // 从列表中移除已删除的处方
      savedPrescriptions.value = savedPrescriptions.value.filter(
        (item) => item.id !== savedItem.id
      );
    } else {
      ElMessage.error("处方删除失败");
    }
  } catch (error) {
    console.error("Failed to delete prescription:", error);
    ElMessage.error("处方删除失败");
  }
};

// 在组件加载时调用
onMounted(() => {
  getDrugsData(); // 获取初始的药品数据
  loadSavedPrescriptions(); // 加载已保存的处方
});
</script>

<style scoped>
.prescription-page {
  padding: 20px;
}

.prescription-list {
  margin-bottom: 20px;
}

.prescription-item {
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}

.saved-prescriptions {
  margin-top: 20px;
}

/* 新增纵向滚动容器样式 */
.saved-prescriptions-scroll {
  max-height: 200px; /* 设置固定高度，可根据需要调整 */
  overflow-y: auto; /* 添加纵向滚动条 */
}

.saved-prescription-item {
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  flex-wrap: nowrap; /* 让字段在同一行显示 */
  overflow-x: auto; /* 添加横向滚动条 */
  white-space: nowrap; /* 防止内容换行 */
}

/* 已保存处方表单项样式 */
.saved-prescription-item .el-form-item {
  margin-bottom: 0;
  margin-right: 5px;
}

.beizhu-wide {
  width: 250px;
}

/* 分隔线样式 */
.separator {
  height: 4px;
  background-color: #999;
  margin: 30px 0;
  border-radius: 2px;
}
</style>